function login() {
    const username = document.getElementById("username").value;
    const password = document.getElementById("password").value;
    if (username.length !== 10) {
        alert("账号长度应为10位！");
        return;
    }
    const user = {"userName": username, "password": CryptoJS.MD5(password).toString()};

    httpRequest("http://172.27.71.125:7402/leave/api/login", JSON.stringify(user),
        response => {
            const res = JSON.parse(response);
            switch (res["msgId"]) {
                case "A001":
                    alert('您输入的用户名不存在');
                    break;
                case "A002":
                    alert('密码错误');
                    break;
                case "A011":
                    // 普通用户登录成功
                    sessionStorage.setItem("token", res["result"]["authtoken"]);
                    sessionStorage.setItem("identity", "0");
                    urlReplace("student.html");
                    break;
                case "A010":
                    // 管理员登录成功
                    sessionStorage.setItem("token", res["result"]["authtoken"]);
                    sessionStorage.setItem("identity", "1");
                    urlReplace("teacher.html");
                    break;
            }
        },
        code => alert("未知错误：" + code));
}

function text_change() {
    const username = document.getElementById("username").value;
    const password = document.getElementById("password").value;

    if (username == null || password == null || username === "" || password === "") {
        button.disabled = "disabled";
    } else {
        button.disabled = "";
    }
}

function do_login(ev) {
    if (ev.keyCode === 13) {
        button.click();
    }
}

window.onload = function () {
    const button = document.getElementById("button");
    const username = document.getElementById("username");
    const password = document.getElementById("password");

    button.addEventListener("click", login);
    username.addEventListener("keydown", ev => do_login(ev));
    username.addEventListener("input", text_change);
    password.addEventListener("keydown", ev => do_login(ev));
    password.addEventListener("input", text_change);
}
